package com.ugoodtech.mdcc.core.utils;

import com.ugoodtech.mdcc.core.Constants;
import org.apache.commons.io.IOUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * User: Kotone
 * Date: 2017-12-18
 * Time: 15:40
 * To change this template use File | Settings | File Templates.
 */
public class WeChatUtil {

    @Value("${wechat.appID}")
    private static String appID;
    @Value("${wechat.appSecret}")
    private static String appSecret;

    public static String getOpenId(String code) {

        System.out.println(appID + "==" + appSecret);
        String weChatUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appID
            + "&secret=" + appSecret + "&grant_type=authorization_code&code=" + code;
        URLConnection urlConnection = null;
        InputStream inputStream = null;
        String body ="";
        try {
            URL url = new URL(weChatUrl);
            urlConnection = url.openConnection();
            urlConnection.setDoOutput(true);
            // 定义待写入数据的内容类型，我们设置为application/x-www-form-urlencoded类型
            urlConnection.setRequestProperty("content-type", "application/json");
            inputStream = urlConnection.getInputStream();
            String encoding = urlConnection.getContentEncoding();
            body= IOUtils.toString(inputStream, encoding);
            JSONObject jsonObject=new JSONObject(body);
            String openId=jsonObject.getString("openid");
            return openId;
        } catch (IOException e) {
            System.out.println(weChatUrl + " 的请求连接失败");
        } catch (JSONException e) {
            System.out.println(weChatUrl + " 的返回json转换失败"+body);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                System.out.println("请求为" + weChatUrl + "输入流关闭失败");
            }
        }
        //todo
        return "testOpenId";
//        throw new Exception("获取失败");
    }


    public static String getAccess_token() {
        String access_token="";

        String weChatUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appID+"&secret="+appSecret;
        URLConnection urlConnection = null;
        InputStream inputStream=null;
        try {
            URL url = new URL(weChatUrl);
            urlConnection = url.openConnection();
            urlConnection.setDoOutput(true);
            // 定义待写入数据的内容类型，我们设置为application/x-www-form-urlencoded类型
            urlConnection.setRequestProperty("content-type", "application/json");
            inputStream = urlConnection.getInputStream();
            String encoding = urlConnection.getContentEncoding();
            String body = IOUtils.toString(inputStream, encoding);
            access_token=body.split("\"")[3];
        } catch (IOException e) {
            System.out.println(weChatUrl+" 的请求连接失败");
        }finally{
            try {
                inputStream.close();
            } catch (IOException e) {
                System.out.println("请求为"+weChatUrl+"输入流关闭失败");
            }
        }
        return access_token;
    }


    public static boolean pushMessage(String openId,String template_id,String directUrl,String data) {
       Map<String ,Object> map=new HashMap<>();
        map.put("touser",openId);
        map.put("template_id",template_id);
        map.put("url",directUrl);
        Map<String ,Object> map2=new HashMap<>();
        Map<String ,Object> map3=new HashMap<>();
        Map<String ,Object> map4=new HashMap<>();
        Map<String ,Object> map5=new HashMap<>();
        Map<String ,Object> map6=new HashMap<>();

        map3.put("value","系统消息");
        map4.put("value",data);
        map5.put("value",new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT).format(new Date()));
        map6.put("value","");

        map2.put("first",map3);
        map2.put("keyword1",map4);
        map2.put("keyword2",map5);
        map2.put("remark",map6);

        map.put("data",map2);
        String accessToken= WeChatUtil.getAccess_token();

        PrintWriter out = null;
        System.out.println(appID + "==" + appSecret);
        String weChatUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + accessToken;
        URLConnection urlConnection = null;
        InputStream inputStream = null;
        String body ="";
        try {
            URL url = new URL(weChatUrl);
            urlConnection = url.openConnection();
            // 定义待写入数据的内容类型，我们设置为application/x-www-form-urlencoded类型
            urlConnection.setRequestProperty("content-type", "application/json");
            urlConnection.setDoOutput(true);
            urlConnection.setDoInput(true);
            out = new PrintWriter(urlConnection.getOutputStream());

            System.out.println(new JSONObject(map).toString());
            out.print(new JSONObject(map).toString());
            out.flush();

            inputStream = urlConnection.getInputStream();
            String encoding = urlConnection.getContentEncoding();
            body= IOUtils.toString(inputStream, encoding);
            System.out.println(body);
            JSONObject jsonObject=new JSONObject(body);
            int errcode=jsonObject.getInt("errcode");
            if(0==errcode){
                return true;
            }else{
                return false;
            }
        } catch (IOException e) {
            System.out.println(weChatUrl + " 的请求连接失败");
        } catch (JSONException e) {
            System.out.println(weChatUrl + " 的返回json转换失败"+body);
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                System.out.println("请求为" + weChatUrl + "输入流关闭失败");
            }
        }
        return false;
        //todo
//        throw new Exception("获取失败");
    }
}
